<script setup lang="ts">
import { onMounted, ref } from 'vue'
// 组件
import { ElMessage, ElMessageBox } from 'element-plus'
import Form from './dialog/Form/index.vue'
// 接口
import type { IMenuData, IMenuResponseData } from '@/api/system/menu/type'
import type { ResponseData } from '@/types/common'
// api
import { reqMenuList, reqMenuDel } from '@/api/system/menu/index'
// 列表数据
let tableData = ref<IMenuData[]>([])
// 弹窗
let dialogVisible = ref<boolean>(false)

// 子组件实例
const formRef = ref()
// 获取菜单列表
const getList = async () => {
  const { code, data, message }: IMenuResponseData = await reqMenuList()
  if (code === 200) {
    tableData.value = data
  } else {
    ElMessage({
      type: 'error',
      message,
    })
  }
}
// 新增菜单
const handleAdd = () => {
  dialogVisible.value = true
}
// 新增子菜单
const handleAddChild = (row: IMenuData) => {
  formRef.value.setFormData(row, 0)
  dialogVisible.value = true
}
// 修改菜单
const handleEdit = (row: IMenuData) => {
  formRef.value.setFormData(row, 1)
  dialogVisible.value = true
}
// 删除菜单
const handleDel = (row: IMenuData) => {
  ElMessageBox.confirm('确定删除这条数据吗', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const { code, message }: ResponseData = await reqMenuDel(row.id)
    if (code === 200) {
      ElMessage({
        type: 'success',
        message,
      })
      getList()
    } else {
      ElMessage({
        type: 'error',
        message,
      })
    }
  })
}
onMounted(() => {
  getList()
})
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-header>
      <el-main>
        <el-table :data="tableData" row-key="id" border>
          <el-table-column prop="name" label="菜单名称" align="center" />
          <el-table-column prop="code" label="资源编码" align="center" />
          <el-table-column label="操作" align="center">
            <template #="scope">
              <el-button type="primary" link @click="handleAddChild(scope.row)">
                新增
              </el-button>
              <el-button type="primary" link @click="handleEdit(scope.row)">
                修改
              </el-button>
              <el-button type="danger" link @click="handleDel(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer></el-footer>
    </el-container>
    <Form ref="formRef" v-model="dialogVisible" @refresh-list="getList"></Form>
  </div>
</template>
